package com.danielagarza.app;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.danielagarza.app.modelos.Persona;
import com.danielagarza.app.modelos.PersonaFacebookAuxiliar;
import com.danielagarza.app.servicios.LeerJSON;
import com.danielagarza.app.servicios.PublicarDatos;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import com.google.gson.Gson;

public class Portada extends Fragment {

	private Button buttonLoginLogout;
	private Session.StatusCallback statusCallback = new SessionStatusCallback();
	private ProfilePictureView profilePictureView;
	private UiLifecycleHelper uiHelper;
	private static final int REAUTH_ACTIVITY_CODE = 100;

	public Portada() {
		// TODO Auto-generated constructor stub
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(final Session session, final SessionState state,
				final Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View vista;
		DisplayMetrics metrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);
		if (metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
				|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM) {
			vista = inflater.inflate(R.layout.activity_portada, container,
					false);
		} else {
			vista = inflater.inflate(R.layout.activity_portada_tablet,
					container, false);
		}

		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);
		buttonLoginLogout = (Button) vista.findViewById(R.id.login_button);
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
		profilePictureView = (ProfilePictureView) vista
				.findViewById(R.id.selection_profile_pic);
		profilePictureView.setCropped(true);

		Session session = Session.getActiveSession();
		if (session == null) {
			if (savedInstanceState != null) {
				session = Session.restoreSession(getActivity(), null,
						statusCallback, savedInstanceState);
			}
			if (session == null) {
				session = new Session(getActivity());
			}
			Session.setActiveSession(session);
			if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
				session.openForRead(new Session.OpenRequest(this)
						.setCallback(statusCallback));
			}
		}

		updateView();

		if (session != null && session.isOpened()) {
			// Get the user's data
			makeMeRequest(session);
		}

		return vista;
	}

	@Override
	public void onStart() {
		super.onStart();
		Session.getActiveSession().addCallback(statusCallback);
	}

	@Override
	public void onStop() {
		super.onStop();
		Session.getActiveSession().removeCallback(statusCallback);
		uiHelper.onPause();

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(getActivity(), requestCode,
				resultCode, data);
		if (requestCode == REAUTH_ACTIVITY_CODE) {
			uiHelper.onActivityResult(requestCode, resultCode, data);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
		uiHelper.onSaveInstanceState(outState);
	}

	private void updateView() {
		Session session = Session.getActiveSession();
		if (session.isOpened()) {
			buttonLoginLogout.setText(R.string.logout);
			buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					onClickLogout();
				}
			});
		} else {
			// txt.setText(R.string.instructions);
			buttonLoginLogout.setText(R.string.login);
			buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					onClickLogin();
				}
			});
		}
	}

	private void onClickLogin() {
		Session session = Session.getActiveSession();
		if (!session.isOpened() && !session.isClosed()) {
			session.openForRead(new Session.OpenRequest(this)
					.setCallback(statusCallback));
		} else {
			Session.openActiveSession(getActivity(), this, true, statusCallback);
		}
	}

	private void onClickLogout() {
		Session session = Session.getActiveSession();
		if (!session.isClosed()) {
			session.closeAndClearTokenInformation();

		}
	}

	private class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			updateView();
		}
	}

	private void makeMeRequest(final Session session) {
		// Make an API call to get user data and define a
		// new callback to handle the response.
		Request request = Request.newMeRequest(session,
				new Request.GraphUserCallback() {

					@Override
					public void onCompleted(GraphUser user, Response response) {
						// If the response is successful
						if (session == Session.getActiveSession()) {
							if (user != null) {
								// Set the id for the ProfilePictureView
								// view that in turn displays the profile
								// picture.
								profilePictureView.setProfileId(user.getId());
									Persona persona = new Persona(user.getId(),
											user.getFirstName(), user
													.getMiddleName() +" "+ user.getLastName(), user
													.getBirthday(), "PRI", "",
											user.getLink());
									PostData publicar = new PostData(persona, session);
									publicar.execute();

							}
						}
						if (response.getError() != null) {
							// Handle errors, will do so later.
						}

					}
				});
		request.executeAsync();
	}

	private void onSessionStateChange(final Session session,
			SessionState state, Exception exception) {
		if (session != null && session.isOpened()) {
			// Get the user's data.
			makeMeRequest(session);
		}
	}
	


	private class PostData extends AsyncTask<Void, Void, Void> {
		Persona p;
		Session sesion;

		public PostData(Persona p, Session sesion) {
			this.p = p;
			this.sesion = sesion;
		}

		@Override
		protected Void doInBackground(Void... arg) {
			try{
				String valor = LeerJSON
						.leerJSON("https://graph.facebook.com/"+p.getIdFacebook()+
								"?fields=id,email,picture,political,gender&&access_token="+sesion.getAccessToken());
				
				Gson g = new Gson();
				PersonaFacebookAuxiliar aux = g.fromJson(valor, PersonaFacebookAuxiliar.class);
				p.setCorreo(aux.email);
				p.setaPolitica(aux.political);
				p.setFotoURL(aux.picture.data.url);
				p.setGenero(aux.gender);
				System.out.println("......>"+aux.picture.data.url);
				
				PublicarDatos publicar = new PublicarDatos();
				Persona persona = publicar.registrarUsuarios(p);
				
				System.out.println("......>"+persona.getFotoURL());

			}catch(Exception ex){
				System.out.print("hola "+ex.getMessage());
			}
			return null;

		}
	}

}
